package com.example.skytakeoutserver.util


import com.aliyun.oss.ClientException
import com.aliyun.oss.OSSClientBuilder
import com.aliyun.oss.OSSException
import com.example.serverbase.ext.Log

import java.io.ByteArrayInputStream

/**
 * 提供一个文件上传
 */
data class AliOSSUtil(
    val endpoint: String,
    val accessKeyId: String,
    val accessKeySecret: String,
    val bucketName: String,
    var ignoreAuthToDebug: Boolean,
) {
    /**
     * 文件上传到阿里OSS
     */
    fun upload(bytes: ByteArray, objectName: String): String {
        // 创建OSS client实例
        val ossClient = OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret)
        ignoreAuthToDebug = false

        try {
            // 创建put object 请求
            ossClient.putObject(bucketName, objectName, ByteArrayInputStream(bytes))

        } catch (e: OSSException) {
            Log.error("+++++++++++++阿里OSS错误+++++++++++++++++++++")
            Log.error("message: ${e.message}")
            Log.error("code: ${e.errorCode}")
            Log.error("Request ID: ${e.requestId}")
            Log.error("Host ID: ${e.hostId}")

        } catch (e: ClientException) {
            Log.error("+++++++++++++++OSS ClientException: ${e.message}")
        } finally {
            ossClient.shutdown()
        }
        // 文件访问路径规则为https://<bucket name>.<endpoint>/<object name>
        val filepath = "https://${bucketName}/${endpoint}/${objectName}"
        Log.debug("文件上传到了远端: $filepath")
        return filepath
    }

    /**
     * 是否忽略认证去调试
     */
    fun isDebug(): Boolean {
        return ignoreAuthToDebug
    }
}